package com.it.demo.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/servletCookie")
public class ServletCookie extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 第一次没有Cookie 打印null ;
		Cookie[] cs = request.getCookies();
		if (cs != null && cs.length != 0) {
			for (Cookie c : cs) {
				System.out.println(c.getName() + ":" + c.getValue());

				response.setContentType("text/html;charset=utf-8");
				PrintWriter out = response.getWriter();
				out.println(c.getName() + ":" + c.getValue());
			}
		}
		// 向返回的response 中添加 cookies 接下来打印设置的cookies
		Cookie c = new Cookie("cookies", " cookies_value_www.it.com");
		c.setMaxAge(60 * 60 * 24 * 7);
		response.addCookie(c);
	}

}
